/* eslint-disable no-promise-executor-return */
import { EventEmitter, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { MetadataService } from '../service/metadata.service';
import { BuilderConfig } from '../models/builder-config';

@Injectable({
    providedIn: 'root'
})
export class ImportExportService {
    constructor(private metaRepository: MetadataService, private route: Router) {}

    private savedMetadata: BuilderConfig = {};

    private normalizedMetadata: BuilderConfig = {};

    changed = new EventEmitter();

    /**
     * 导入元数据
     * @param meta
     * @param redirectView
     */
    importMetadata(meta: string, redirectView: string): Promise<void> {
        this.clearSavedMetadata();
        try {
            this.savedMetadata = JSON.parse(meta);
        } catch {
            return new Promise((_, reject): void => reject());
        }
        this.normalizedMetadata = { ...this.savedMetadata };
        /**
         * 传入的元数据和实际需要的元数据需要经过转化，保证格式一致性
         */

        return this.metaRepository
            .import(
                {
                    name: this.normalizedMetadata.themeName,
                    colorScheme: this.normalizedMetadata.colorScheme
                },
                this.savedMetadata.items
            )
            .then(() => {
                // themeName主题名称  colorScheme 当前主题下的颜色类型
                this.route.navigate([redirectView, this.normalizedMetadata.themeName, this.normalizedMetadata.colorScheme]);
                this.changed.emit();
            });
    }

    /**
     * 导出元数据
     * @param customSchemeName
     * @param useSwatch
     * @param widgets
     * @param removeExternalResources
     */
    exportMetadata(customSchemeName: string, useSwatch: boolean, widgets: string[], removeExternalResources: boolean): Promise<string> {
        const SPACES_NUMBER = 4;

        return this.metaRepository.getVersion().then((version) => {
            const exportedObject = {
                ...this.savedMetadata,
                items: this.metaRepository.getModifiedItems(),
                baseTheme: [this.metaRepository.theme.name, this.metaRepository.theme.colorScheme.replace(/-/g, '.')].join('.'),
                outputColorScheme: customSchemeName,
                makeSwatch: useSwatch,
                version,
                widgets,
                removeExternalResources
            };

            return JSON.stringify(exportedObject, null, SPACES_NUMBER);
        });
    }

    /**
     * 导出样式
     * @param customSchemeName
     * @param useSwatch
     * @param widgets
     * @param removeExternalResources
     */
    exportCss(themeName = ''): Promise<string> {
        //customSchemeName, useSwatch, widgets, this.savedMetadata.assetsBasePath, removeExternalResources
        return this.metaRepository.export(themeName);
    }

    getSavedMetadata(): BuilderConfig {
        return this.savedMetadata;
    }

    getColorSchemeName(): string {
        return this.normalizedMetadata.outColorScheme || 'custom-scheme';
    }

    getThemeName(): string {
        return this.metaRepository.theme.name;
    }

    getWidgets(): Array<string> {
        return this.normalizedMetadata.widgets;
    }

    /**
     * 清空保存的修改
     */
    clearSavedMetadata(): void {
        this.savedMetadata = {};
        this.normalizedMetadata = {};
        this.changed.emit();
    }
}
